import { setting } from "@/config/config";
import axios from "axios";
import message from "element-ui/packages/message";
import { Message } from "element-ui";

const contentType = "application/json;charset=UTF-8";
const baseURL = setting.Host;

const service = axios.create({
  baseURL: baseURL,
  timeout: 30 * 10000,
  headers: {
    "Content-Type": contentType
  }
});

let loadingCount = 0;
let loading;
const startLoading = () => {
  loading = Message({
    duration: 0,
    message: "加载中",
    center: true,
    iconClass: "el-icon-loading",
    customClass: "loading-message"
  });
};
const endLoading = () => {
  loading.close();
};
const showLoading = () => {
  if (loadingCount === 0) {
    startLoading();
  }
  loadingCount += 1;
};

const hideLoading = () => {
  if (loadingCount <= 0) {
    return;
  }
  loadingCount -= 1;
  if (loadingCount === 0) {
    endLoading();
  }
};

const DataToQuery = data => {
  const empty = data => {
    return typeof data === "number" ? false : !data;
  };
  return typeof data === "object"
    ? "?" +
        Object.keys(data)
          .filter(k => !empty(data[k]))
          .map(k => `${k}=${data[k]}`)
          .join("&")
    : "";
};
service.interceptors.request.use(
  config => {
    showLoading();
    if (config.url == "/api/v1/interface/dynamic") {
      config.hidetoast = true;
    }
    if (config.method == "get") {
      config.url = `${config.url}${DataToQuery(config.data)}`;
    } else {
      config.data = JSON.stringify(config.data);
    }
    config.headers = Object.assign(config.headers, {
      AdminToken: localStorage.getItem("Admin_token")
    });

    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

//响应拦截器
service.interceptors.response.use(
  response => {
    hideLoading();
    return new Promise((success, fail) => {
      if (response.data.code === 200) {
        success(response);
      } else {
        if (response.data.code !== undefined) {
          if (!response.config.hidetoast) {
            message.error(response.data.message);
          }
          fail(response);
        } else {
          success(response);
        }
      }
    });
  },
  error => {
    hideLoading();
    if (
      error.code === "ECONNABORTED" ||
      error.message === "Network Error" ||
      error.message.includes("timeout")
    ) {
      message.error("请求超时，请稍后重试");
    }
    return Promise.resolve(error.response);
  }
);

export default service;
